#include "RobotCtrl.h"

#define NUM_ANIMS 7


RobotCtrl::RobotCtrl( Ogre::SceneManager* smgr,Ogre::String name ):m_Smgr(smgr)
{
	m_Node = m_Smgr->getSceneNode(name);
	m_Ent = m_Smgr->getEntity(name);
	m_MovSpeed = 10;
	m_AnimSpeed = 0.3;
	m_CurrentAnimID = ANIM_STANT_STAND;
	Init();
}

RobotCtrl::~RobotCtrl(void)
{
}

void RobotCtrl::Init()
{
	m_Ent->getSkeleton()->setBlendMode(Ogre::ANIMBLEND_CUMULATIVE);
	Ogre::String animNames[] =
	{"Run", "Walk", "Sprint", "Stand", "Stand1", "Stand2", "Stand3"};

	for (int i = 0; i < NUM_ANIMS; i++)
	{
		m_Anims[i] = m_Ent->getAnimationState(animNames[i]);
		if (animNames[i].substr(0, 5) == "Stand")
			m_Anims[i]->setLoop(false);
		else
			m_Anims[i]->setLoop(true);
	}
}

void RobotCtrl::RunAndAttack( Ogre::Vector3 movtag, Ogre::Vector3 attacktag )
{
	m_CurrenTarget = movtag;
	m_AtkTarget = attacktag;
	m_Anims[m_CurrentAnimID]->setEnabled(false);
	m_CurrentAnimID = ANIM_ROBOT_WALK;
	m_Anims[ANIM_ROBOT_WALK]->setEnabled(true);
}

void RobotCtrl::Updata( float deltaTime )
{
	m_Timer += deltaTime;
	m_Anims[m_CurrentAnimID]->addTime(deltaTime*m_AnimSpeed);
	if (m_CurrentAnimID == ANIM_ROBOT_WALK)
	{
		Ogre::Vector3 dif = m_CurrenTarget - m_Node->getPosition();
		float movlen = deltaTime*m_MovSpeed;
		if (dif.length() < 10)
		{
			m_Node->setPosition(m_CurrenTarget);
			m_Anims[m_CurrentAnimID]->setEnabled(false);
			m_CurrentAnimID = ANIM_STANT_STAND2;
			m_Anims[m_CurrentAnimID]->setEnabled(true);
			m_Timer = 0;
		}
		else
		{
			dif.normalise();
			Ogre::Vector3 newpos = dif*movlen + m_Node->getPosition();
			m_Node->setPosition(newpos);
		}
	}

}

float RobotCtrl::GetCurrentAnimTime()
{
	return m_Anims[m_CurrentAnimID]->getTimePosition();
}

bool RobotCtrl::IsAttack()
{
	if (m_CurrentAnimID == ANIM_STANT_STAND2)
	{
		if (m_Timer>1.0f)
			return true;
	}
	return false;
}
